<template>
  <div class="login-register-container">
    <div class="form-container">
      <div class="tabs">
        <div :class="['tab', { active: activeTab === 'login' }]" @click="activeTab = 'login'">
          登录
        </div>
        <div :class="['tab', { active: activeTab === 'register' }]" @click="activeTab = 'register'">
          注册
        </div>
      </div>

      <!-- 登录表单 -->
      <div v-if="activeTab === 'login'" class="form">
        <h2>用户登录</h2>
        <div class="form-group">
          <label for="login-phone">手机号码</label>
          <input
            id="login-phone"
            v-model="loginForm.phone"
            type="text"
            placeholder="请输入手机号码"
          />
          <div v-if="loginErrors.phone" class="error-message">{{ loginErrors.phone }}</div>
        </div>

        <div class="form-group">
          <label for="login-password">密码</label>
          <input
            id="login-password"
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
          />
          <div v-if="loginErrors.password" class="error-message">{{ loginErrors.password }}</div>
        </div>

        <button @click="handleLogin" :disabled="isLoginLoading" class="submit-btn">
          {{ isLoginLoading ? '登录中...' : '登录' }}
        </button>

        <div v-if="loginError" class="global-error">{{ loginError }}</div>
      </div>

      <!-- 注册表单 -->
      <div v-if="activeTab === 'register'" class="form">
        <h2>用户注册</h2>

        <div class="form-group">
          <label for="register-phone">手机号码</label>
          <input
            id="register-phone"
            v-model="registerForm.phone"
            type="text"
            placeholder="请输入手机号码"
          />
          <div v-if="registerErrors.phone" class="error-message">{{ registerErrors.phone }}</div>
        </div>

        <div class="form-group">
          <label for="register-password">密码</label>
          <input
            id="register-password"
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
          />
          <div v-if="registerErrors.password" class="error-message">
            {{ registerErrors.password }}
          </div>
        </div>

        <div class="form-group">
          <label for="register-confirm-password">确认密码</label>
          <input
            id="register-confirm-password"
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
          />
          <div v-if="registerErrors.confirmPassword" class="error-message">
            {{ registerErrors.confirmPassword }}
          </div>
        </div>

        <div class="form-group">
          <label for="register-idcard">身份证号</label>
          <input
            id="register-idcard"
            v-model="registerForm.idCard"
            type="text"
            placeholder="请输入身份证号"
          />
          <div v-if="registerErrors.idCard" class="error-message">{{ registerErrors.idCard }}</div>
        </div>

        <div class="form-group">
          <label for="register-email">电子邮箱</label>
          <input
            id="register-email"
            v-model="registerForm.email"
            type="email"
            placeholder="请输入电子邮箱"
          />
          <div v-if="registerErrors.email" class="error-message">{{ registerErrors.email }}</div>
        </div>

        <!-- 地区选择 -->
        <div class="location-selects">
          <div class="form-group">
            <label for="province">省份</label>
            <select id="province" v-model="registerForm.provinceCode">
              <option value="">请选择省份</option>
              <option value="15">河北省</option>
              <option value="11">北京市</option>
              <!-- 更多省份选项 -->
            </select>
            <div v-if="registerErrors.provinceCode" class="error-message">
              {{ registerErrors.provinceCode }}
            </div>
          </div>

          <div class="form-group">
            <label for="city">城市</label>
            <select id="city" v-model="registerForm.cityCode">
              <option value="">请选择城市</option>
              <option value="15">石家庄</option>
              <option value="16">保定</option>
              <!-- 更多城市选项 -->
            </select>
            <div v-if="registerErrors.cityCode" class="error-message">
              {{ registerErrors.cityCode }}
            </div>
          </div>

          <div class="form-group">
            <label for="county">区县</label>
            <select id="county" v-model="registerForm.countyCode">
              <option value="">请选择区县</option>
              <option value="20">新华区</option>
              <option value="21">桥西区</option>
              <!-- 更多区县选项 -->
            </select>
            <div v-if="registerErrors.countyCode" class="error-message">
              {{ registerErrors.countyCode }}
            </div>
          </div>

          <div class="form-group">
            <label for="township">乡镇</label>
            <select id="township" v-model="registerForm.townshipCode">
              <option value="">请选择乡镇</option>
              <option value="7">示例乡镇1</option>
              <option value="8">示例乡镇2</option>
              <!-- 更多乡镇选项 -->
            </select>
            <div v-if="registerErrors.townshipCode" class="error-message">
              {{ registerErrors.townshipCode }}
            </div>
          </div>

          <div class="form-group">
            <label for="village">村庄</label>
            <select id="village" v-model="registerForm.villageCode">
              <option value="">请选择村庄</option>
              <option value="3">示例村庄1</option>
              <option value="4">示例村庄2</option>
              <!-- 更多村庄选项 -->
            </select>
            <div v-if="registerErrors.villageCode" class="error-message">
              {{ registerErrors.villageCode }}
            </div>
          </div>
        </div>

        <div class="form-group">
          <label for="register-department">部门名称</label>
          <input
            id="register-department"
            v-model="registerForm.departmentName"
            type="text"
            placeholder="请输入部门名称"
          />
          <div v-if="registerErrors.departmentName" class="error-message">
            {{ registerErrors.departmentName }}
          </div>
        </div>

        <button @click="handleRegister" :disabled="isRegisterLoading" class="submit-btn">
          {{ isRegisterLoading ? '注册中...' : '注册' }}
        </button>

        <div v-if="registerError" class="global-error">{{ registerError }}</div>
      </div>
    </div>
  </div>
</template>
  
  <script>
import { mapActions } from 'vuex'
import { loginUser, registerUser } from '@/api/login_register'

export default {
  name: 'LoginRegister',
  data() {
    return {
      activeTab: 'login',

      // 登录表单
      loginForm: {
        phone: '',
        password: '',
      },
      loginErrors: {
        phone: '',
        password: '',
      },
      loginError: '',
      isLoginLoading: false,

      // 注册表单
      registerForm: {
        phone: '',
        password: '',
        confirmPassword: '',
        idCard: '',
        email: '',
        provinceCode: '',
        cityCode: '',
        countyCode: '',
        townshipCode: '',
        villageCode: '',
        departmentName: '',
      },
      registerErrors: {
        phone: '',
        password: '',
        confirmPassword: '',
        idCard: '',
        email: '',
        provinceCode: '',
        cityCode: '',
        countyCode: '',
        townshipCode: '',
        villageCode: '',
        departmentName: '',
      },
      registerError: '',
      isRegisterLoading: false,
    }
  },
  methods: {
    ...mapActions(['setUserInfo', 'setToken']),

    // 验证登录表单
    validateLoginForm() {
      let isValid = true
      this.loginErrors = {
        phone: '',
        password: '',
      }

      if (!this.loginForm.phone) {
        this.loginErrors.phone = '请输入手机号码'
        isValid = false
      } else if (!/^1[3-9]\d{9}$/.test(this.loginForm.phone)) {
        this.loginErrors.phone = '请输入有效的手机号码'
        isValid = false
      }

      if (!this.loginForm.password) {
        this.loginErrors.password = '请输入密码'
        isValid = false
      }

      return isValid
    },

    // 处理登录 - Promise .then 风格
    handleLogin() {
      if (!this.validateLoginForm()) {
        return
      }

      this.isLoginLoading = true
      this.loginError = ''

      const loginData = {
        phone: this.loginForm.phone,
        password: this.loginForm.password,
      }

      loginUser(loginData)
        .then((response) => {
          if (response.data) {
            // 登录成功
            // alert('success')
            this.$store.dispatch('setUserInfo', response.data.userInfo || {})
            this.$store.dispatch('setToken', response.data.token)

            this.$router.push('/home')
          } else {
            this.loginError = '登录失败，请稍后重试'
          }
        })
        .catch((error) => {
          //   alert('fail')
          console.error('登录错误:', error)
          this.loginError = error.response?.data?.message || '登录失败，请稍后重试'
        })
        .finally(() => {
          //   alert('fina')
          this.isLoginLoading = false
        })
    },

    // 验证注册表单
    validateRegisterForm() {
      let isValid = true
      this.registerErrors = {
        phone: '',
        password: '',
        confirmPassword: '',
        idCard: '',
        email: '',
        provinceCode: '',
        cityCode: '',
        countyCode: '',
        townshipCode: '',
        villageCode: '',
        departmentName: '',
      }

      // 验证手机号
      if (!this.registerForm.phone) {
        this.registerErrors.phone = '请输入手机号码'
        isValid = false
      } else if (!/^1[3-9]\d{9}$/.test(this.registerForm.phone)) {
        this.registerErrors.phone = '请输入有效的手机号码'
        isValid = false
      }

      // 验证密码
      if (!this.registerForm.password) {
        this.registerErrors.password = '请输入密码'
        isValid = false
      } else if (this.registerForm.password.length < 6) {
        this.registerErrors.password = '密码长度至少6位'
        isValid = false
      }

      // 验证确认密码
      if (!this.registerForm.confirmPassword) {
        this.registerErrors.confirmPassword = '请确认密码'
        isValid = false
      } else if (this.registerForm.password !== this.registerForm.confirmPassword) {
        this.registerErrors.confirmPassword = '两次输入的密码不一致'
        isValid = false
      }

      // 验证身份证号
      if (!this.registerForm.idCard) {
        this.registerErrors.idCard = '请输入身份证号'
        isValid = false
      } else if (!/^\d{17}[\dXx]$/.test(this.registerForm.idCard)) {
        this.registerErrors.idCard = '请输入有效的身份证号'
        isValid = false
      }

      // 验证邮箱
      if (!this.registerForm.email) {
        this.registerErrors.email = '请输入电子邮箱'
        isValid = false
      } else if (!/^[\w.-]+@[\w.-]+\.\w+$/.test(this.registerForm.email)) {
        this.registerErrors.email = '请输入有效的电子邮箱'
        isValid = false
      }

      // 验证省份
      if (!this.registerForm.provinceCode) {
        this.registerErrors.provinceCode = '请选择省份'
        isValid = false
      }

      // 验证城市
      if (!this.registerForm.cityCode) {
        this.registerErrors.cityCode = '请选择城市'
        isValid = false
      }

      // 验证区县
      if (!this.registerForm.countyCode) {
        this.registerErrors.countyCode = '请选择区县'
        isValid = false
      }

      // 验证乡镇
      if (!this.registerForm.townshipCode) {
        this.registerErrors.townshipCode = '请选择乡镇'
        isValid = false
      }

      // 验证村庄
      if (!this.registerForm.villageCode) {
        this.registerErrors.villageCode = '请选择村庄'
        isValid = false
      }

      // 验证部门名称
      if (!this.registerForm.departmentName) {
        this.registerErrors.departmentName = '请输入部门名称'
        isValid = false
      }

      return isValid
    },

    // 处理注册
    async handleRegister() {
      if (!this.validateRegisterForm()) {
        return
      }

      this.isRegisterLoading = true
      this.registerError = ''

      try {
        // 按照后端要求的格式构建注册数据
        const registerData = {
          phone: this.registerForm.phone,
          password: this.registerForm.password,
          confirmPassword: this.registerForm.confirmPassword,
          idCard: this.registerForm.idCard,
          email: this.registerForm.email,
          provinceCode: this.registerForm.provinceCode,
          cityCode: this.registerForm.cityCode,
          countyCode: this.registerForm.countyCode,
          townshipCode: this.registerForm.townshipCode,
          villageCode: this.registerForm.villageCode,
          departmentName: this.registerForm.departmentName,
        }

        // 调用注册API
        const response = await registerUser(registerData)

        // 处理成功注册
        if (response.data && response.data.success) {
          // 显示成功消息
          this.registerError = ''

          // 切换到登录界面
          this.activeTab = 'login'

          // 可选：自动填充登录表单
          this.loginForm.phone = this.registerForm.phone
          this.loginForm.password = ''

          // 重置注册表单
          this.resetRegisterForm()

          // 显示成功提示（可以使用提示组件）
          alert('注册成功，请登录')
        } else {
          this.registerError = '注册失败，请稍后重试'
        }
      } catch (error) {
        console.error('注册错误:', error)
        this.registerError = error.response?.data?.message || '注册失败，请稍后重试'
      } finally {
        this.isRegisterLoading = false
      }
    },

    // 重置注册表单
    resetRegisterForm() {
      this.registerForm = {
        phone: '',
        password: '',
        confirmPassword: '',
        idCard: '',
        email: '',
        provinceCode: '',
        cityCode: '',
        countyCode: '',
        townshipCode: '',
        villageCode: '',
        departmentName: '',
      }
      this.registerErrors = {
        phone: '',
        password: '',
        confirmPassword: '',
        idCard: '',
        email: '',
        provinceCode: '',
        cityCode: '',
        countyCode: '',
        townshipCode: '',
        villageCode: '',
        departmentName: '',
      }
      this.registerError = ''
    },
  },
}
</script>
  
  <style scoped>
.login-register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.form-container {
  width: 100%;
  max-width: 500px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.tabs {
  display: flex;
  border-bottom: 1px solid #eee;
}

.tab {
  flex: 1;
  text-align: center;
  padding: 15px;
  cursor: pointer;
  font-weight: 500;
  color: #666;
  transition: all 0.3s;
}

.tab.active {
  color: #1890ff;
  border-bottom: 2px solid #1890ff;
}

.form {
  padding: 20px;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #333;
}

input,
select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

input:focus,
select:focus {
  outline: none;
  border-color: #1890ff;
}

.location-selects {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  margin-top: 10px;
  transition: background-color 0.3s;
}

.submit-btn:hover {
  background-color: #40a9ff;
}

.submit-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.error-message {
  color: #f5222d;
  font-size: 12px;
  margin-top: 5px;
}

.global-error {
  text-align: center;
  color: #f5222d;
  margin-top: 15px;
}
</style>